import Base from "../base.js";
import AdminsApi from "../../api/admins.js"

export default class extends Base {
    render() {
        this.$el.html(`
            <header class="login">
                <p>后台管理系统</p>
            </header>

            <div class="login-box">
                <p class="title">登录</p>
                <div class="layui-form-item">
                    <label class="layui-form-label">请输入账户</label>
                    <div class="layui-input-inline">
                        <input type="text" name="adminName" required="" lay-verify="required" placeholder="请输入账户" autocomplete="off" class="layui-input">
                    </div>
                </div>
                <div class="layui-form-item">
                    <label class="layui-form-label">请输入密码</label>
                    <div class="layui-input-inline">
                        <input type="password" name="adminPassword" required="" lay-verify="required" placeholder="请输入密码" autocomplete="off" class="layui-input">
                    </div>
                </div>
                <div class="layui-form-item">
                    <div class="layui-input-block">
                        <button class="layui-btn login-btn" lay-submit="" lay-filter="formDemo">登录</button>
                        <button type="reset" class="layui-btn layui-btn-primary">
                            <a href="http://localhost:8081/#/reg">注册</a>
                        </button>
                    </div>
                </div>
            </div>
        `)
        this.loginBtn = $(".login-btn");
        this.adminName = $("input[name=adminName]")
        this.adminPassword = $("input[name=adminPassword]")
    }
    async loginFn() {
        const data = {
            adminName: this.adminName.val(),
            adminPassword: this.adminPassword.val()
        }
        if (data.adminName && data.adminPassword) {
            const flag = await AdminsApi.adminLogin(data);
            if (flag) {
                layer.msg('登录成功', {
                    offset: '15rem'
                    , icon: 1
                    , time: 1500
                }, function () {
                    sessionStorage.setItem("admin_id", flag._id);
                    location.hash = "#/info"
                });
            } else {
                layer.msg('登录失败', {
                    offset: '15rem'
                    , icon: 2
                    , time: 1500
                })
            }
        } else {
            layer.msg('输入框不能为空', {
                offset: '15rem'
                , icon: 2
                , time: 1500
            })
        }


    }
    handle() {
        this.loginBtn.on("click", this.loginFn.bind(this))
    }
}